'''
Created on 25/03/2009

@author: eh01
'''
from im.ds import dsconstants
from im.event.eventhandler import BaseEventHandler

class IMHTTPResponseHandler(BaseEventHandler):
    '''
    Creates the response for all successful HTTP requests
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def do(self, data):
        dso = data

        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()
        
        response_code = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_RESPONSE_CODE).get_literal()
        content_type = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_RESPONSE_CONTENT_TYPE).get_literal()
        body = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_RESPONSE_BODY).get_literal()
        try:            
            # write the response               
            http_request.send_response(response_code)
            http_request.send_header('Content-type', content_type)
            http_request.end_headers()         
            http_request.wfile.write(body)                
        finally:
            lock.release()